/**
 * 
 */
package reco.db.validation;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Arrays;
import java.util.Collection;

import reco.db.Constraint;

/**
 * @author juanjo
 */
public class InConstraint<T> extends Constraint<T> {

    private final Object[] elements;
    private Object[] errorArguments;

    public InConstraint(Collection<? extends T> permittedElements) {
        super("in", "notIn");
        checkNotNull(permittedElements, "permittedElements");
        checkArgument(!permittedElements.isEmpty(), "permittedElements can not be empty");
        this.elements = permittedElements.toArray();
    }

    public InConstraint(T... permittedElements) {
        super("in", "notIn");
        checkNotNull(permittedElements, "permittedElements");
        checkArgument(permittedElements.length > 0, "permittedElements can not be empty");
        this.elements = permittedElements.clone();
    }

    @Override
    public boolean validate(T value) {
        if (value == null) {
            return true;
        }

        for (final Object element : this.elements) {
            if (value.equals(element)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object[] getErrorArguments() {
        if (this.errorArguments == null) {
            this.errorArguments = new Object[] { Arrays.asList(this.elements) };
        }
        return this.errorArguments;
    }
}
